<script setup>
import { ref, reactive } from 'vue';
import { ElMessage, ElForm, ElFormItem, ElInput, ElUpload, ElButton, ElIcon } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { userManager } from '@/utils/user';
import creditService from '@/services/creditService';
import { myRequest } from '@/utils/request';

// 响应式数据
const uploadRef = ref(null); // 获取 el-upload 组件实例
const formRef = ref(null);   // 获取 el-form 组件实例

const certificationForm = reactive({
  applicantId: userManager.getUserId() || '',
  description: '',
  imageUrl: '',
});

const fileList = ref([]); // 用于el-upload的文件列表
const loading = ref(false);

const rules = {
  description: [{ required: true, message: '请输入认证描述', trigger: 'blur' }],
};

// el-upload的图片状态变化回调
const handleFileChange = (uploadFile, uploadFiles) => {
  fileList.value = uploadFiles;
};

// el-upload的图片移除回调
const handleFileRemove = (uploadFile, uploadFiles) => {
  fileList.value = uploadFiles;
};

// 手动上传图片
const uploadImage = async () => {
  const selectedFile = fileList.value.length > 0 ? fileList.value[0].raw : null;
  if (!selectedFile) {
    return null;
  }

  const formData = new FormData();
  formData.append('file', selectedFile);

  try {
    const response = await myRequest.formRequest({
      url: 'images/upload',
      method: 'POST',
      data: formData,
    });
    //
    if (response.code === 1000) {
      return response.data; // 返回图片文件名
    } else {
      //
      ElMessage.error(`图片上传失败: ${response.msg}`);
      return null;
    }
  } catch (error) {
    ElMessage.error(`图片上传过程中发生错误: ${error.message || '未知错误'}`);
    return null;
  }
};

// 提交表单
const submitCertification = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      let finalImageUrl = null;

      if (fileList.value.length > 0) {
        finalImageUrl = await uploadImage();
        if (!finalImageUrl) {
          ElMessage.error('图片上传失败，无法提交申请。');
          loading.value = false;
          return;
        }
      }

      certificationForm.imageUrl = finalImageUrl;

      try {
        const response = await creditService.createCertification(certificationForm);
        //
        if (response.code === 1000) {
          ElMessage.success('学分认证申请提交成功！');
          // 清空表单
          formRef.value.resetFields();
          fileList.value = [];
          certificationForm.imageUrl = '';
        } else {
          //
          ElMessage.error(`申请提交失败: ${response.msg}`);
        }
      } catch (error) {
        console.error('提交认证申请时发生错误:', error);
        ElMessage.error('提交认证申请时发生网络错误，请稍后再试。');
      } finally {
        loading.value = false;
      }
    } else {
      ElMessage.warning('请检查表单输入项！');
    }
  });
};
</script>

<template>
  <div class="credit-certification-page">
    <div class="content-panel">
      <div class="page-header">
        <h1>学分认证申请</h1>
        <p>提交您的学习成果或相关证明，申请学分认证</p>
      </div>

      <el-form
          ref="formRef"
          :model="certificationForm"
          :rules="rules"
          label-position="top"
          class="certification-form"
          @submit.prevent="submitCertification"
      >
        <el-form-item label="认证描述" prop="description">
          <el-input
              v-model="certificationForm.description"
              type="textarea"
              :rows="5"
              placeholder="请详细描述您的学习成果或认证内容，例如：完成了XX课程并通过考试、获得了XX技能证书等。"
              maxlength="500"
              show-word-limit
          />
        </el-form-item>

        <el-form-item label="上传证明图片" prop="imageUrl">
          <el-upload
              ref="uploadRef"
              v-model:file-list="fileList"
              action="#"
              list-type="picture-card"
              :limit="1"
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              accept="image/*"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                请上传清晰的证明材料图片，如证书、成绩单截图等（仅限一张）。
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              @click="submitCertification"
              :loading="loading"
              class="submit-button"
              native-type="submit"
          >
            {{ loading ? '正在提交...' : '提交申请' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
/* 页面整体布局 */
.credit-certification-page {
  padding: 24px;
  background-color: #f7f8fa;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

/* 主内容面板 */
.content-panel {
  width: 100%;
  max-width: 700px;
  background-color: #fff;
  border-radius: 16px;
  padding: 32px 40px;
  box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05), 0 2px 4px -2px rgba(0,0,0,0.05);
}

/* 页面标题 */
.page-header {
  margin-bottom: 24px;
  padding-bottom: 24px;
  border-bottom: 1px solid #e4e7ed;
  text-align: center;
}
.page-header h1 {
  font-size: 22px;
  font-weight: 500;
  color: #202124;
  margin-bottom: 8px;
}
.page-header p {
  font-size: 14px;
  color: #5f6368;
}

/* 表单样式 */
.certification-form {
  margin-top: 24px;
}
.certification-form :deep(.el-form-item__label) {
  color: #3c4043;
  font-weight: 500;
}
.certification-form .el-upload__tip {
  color: #909399;
  font-size: 13px;
  line-height: 1.5;
  margin-top: 8px;
}

/* 提交按钮 */
.submit-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border-radius: 8px;
  margin-top: 16px;
}
</style>